package cn.zyx.sys.web;

import cn.zyx.common.GlobalAjaxJson;
import cn.zyx.common.properites.GlobalProperties;
import cn.zyx.common.utils.sys.UserUtils;
import cn.zyx.sys.entity.Office;
import cn.zyx.sys.entity.User;
import cn.zyx.sys.service.OfficeService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 机构Controller
 *
 * @author zyx
 */
@RestController
@RequestMapping("/sys/office")
@Api(tags ="机构管理")
public class OfficeController {

    @Autowired
    private OfficeService officeService;

    /**
     * 根据id查询office
     * @param id
     * @return
     */
    @GetMapping("office")
    public Office getOfficeById(@RequestParam(required = false) String id) {
        if (StringUtils.isNotBlank (id)) {
            return officeService.getOfficeById(id);
        } else {
            return new Office();
        }
    }

    //@RequiresPermissions("sys:office:list")
    @GetMapping(value = "list")
    public GlobalAjaxJson list(Office office) {
        if (office == null || office.getParentIds () == null) {
            return GlobalAjaxJson.success().put("list", officeService.findList (false));
        } else {
            return GlobalAjaxJson.success().put("list", officeService.findList (office));
        }
    }

    //@RequiresPermissions(value = {"sys:office:view", "sys:office:add", "sys:office:edit"}, logical = Logical.OR)
    @GetMapping("queryById")
    public GlobalAjaxJson queryById(Office office) {
        User user = UserUtils.getUser();
        if (office.getParent () == null || office.getParent().getId () == null) {
            office.setParent (user.getOffice ());
        }
        office.setParent(officeService.getOfficeById(office.getParent().getId()));
        /*if (office.getArea () == null) {
            office.setArea (user.getOffice ().getArea ());
        }*/
        // 自动获取排序号
        if (StringUtils.isBlank (office.getId()) && office.getParent () != null) {
            int size = 0;
            List<Office> list = officeService.findAll();
            for (int i = 0; i < list.size (); i++) {
                Office e = list.get (i);
                if (e.getParent () != null && e.getParent ().getId () != null
                        && e.getParent ().getId ().equals (office.getParent ().getId ())) {
                    size++;
                }
            }
            office.setCode (office.getParent ().getCode () + StringUtils.leftPad (String.valueOf (size > 0 ? size + 1 : 1), 3, "0"));
        }
        return GlobalAjaxJson.success ().put ("office", office);
    }

    //@RequiresPermissions(value = {"sys:office:add", "sys:office:edit"}, logical = Logical.OR)
    @PostMapping("save")
    public GlobalAjaxJson save(Office office) {
        officeService.save (office);
        if (office.getChildDeptList () != null) {
            Office childOffice = null;
            for (String id : office.getChildDeptList ()) {
                childOffice = new Office ();
                //childOffice.setName (DictUtils.getDictLabel (id, "sys_office_common", "未知"));
                childOffice.setParent (office);
                //childOffice.setArea (office.getArea());
                childOffice.setType ("2");
                childOffice.setGrade (String.valueOf (Integer.valueOf (office.getGrade ()) + 1));
                childOffice.setUseable (GlobalProperties.YES);
                officeService.save (childOffice);
            }
        }
        return GlobalAjaxJson.success ("保存机构'" + office.getName () + "'成功");
    }

    //@RequiresPermissions("sys:office:del")
    @DeleteMapping("delete")
    public GlobalAjaxJson delete(String ids) {
        String[] idArray = ids.split(",");
        for (String id : idArray){
            officeService.delete(new Office(id));
        }
        return GlobalAjaxJson.success("删除成功！");
    }


    /**
     * 获取机构树
     *
     * @param extId 排除的ID
     * @param type  类型（1：公司；2：部门/小组/其它）
     * @return
     */
    //@RequiresPermissions("user")
    @GetMapping("treeData")
    public GlobalAjaxJson treeData(@RequestParam(required = false) String extId, @RequestParam(required = false) String type) {
        List<Office> list = officeService.findList();
        List<Office> rootTree = getRootTree (list, extId, type);
        return GlobalAjaxJson.success ().put ("treeData", rootTree);
    }

    private List<Office> getRootTree(List<Office> list, String extId, String type) {
        List<Office> offices = Lists.newArrayList ();
        List<Office> rootTrees = officeService.getChildren ("0");
        for (Office root : rootTrees) {
            if ((StringUtils.isBlank (extId) || (extId != null && !extId.equals (root.getId ()) && root.getParentIds ().indexOf ("," + extId + ",") == -1))
                    && (type == null || (type != null && (type.equals ("1") ? type.equals (root.getType ()) : true)))
                    && GlobalProperties.YES.equals (root.getUseable ())) {
                // 不是被排除节点的子节点
                List<Office> officeList = formatListToTree (root, list, extId, type);
                offices.addAll (officeList);
            }
        }
        return offices;
    }

    public List<Office> formatListToTree(Office root, List<Office> allList, String extId, String type) {
        String rootId = root.getId ();
        // type为2时，是选择部门，因此禁用type为1的公司节点
        if("2".equals(type) && root.getType().equals("1")){
            root.setDisabled(true);
        }else {
            root.setDisabled(false);
        }
        // 最终的树形态
        List<Office> trees = Lists.newArrayList ();
        // 把需要构造树的所有列表, 根据以父id作为key, 整理为列表
        Map<String, List<Office>> treeMap = Maps.newHashMap ();
        for (Office entity : allList) {
            List<Office> offices = treeMap.get(entity.getParent().getId());
            if (offices == null) {
                offices = Lists.newLinkedList ();
            }
            if ((StringUtils.isBlank (extId) || (extId != null && !extId.equals (entity.getId ()) && entity.getParentIds ().indexOf ("," + extId + ",") == -1))
                    && (type == null || (type != null && (type.equals ("1") ? type.equals (entity.getType ()) : true)))
                    && GlobalProperties.YES.equals (entity.getUseable ())) {
                // type为2时，是选择部门，因此禁用type为1的公司节点
                if("2".equals(type) && entity.getType().equals("1")){
                    entity.setDisabled(true);
                }else {
                    entity.setDisabled(false);
                }
                offices.add (entity);
                treeMap.put (entity.getParent ().getId (), offices);
            }
        }
        // 开始递归格式化
        List<Office> children = treeMap.get (rootId);
        if (children != null) {
            for (Office parent : children) {
                formatFillChildren (parent, treeMap);
                trees.add (parent);
            }
        }
        root.setChildren (trees);
        return Lists.newArrayList (root);
    }

    /**
     * 从treeMap中取出子节点填入parent, 并递归此操作
     **/
    private void formatFillChildren(Office parent, Map<String, List<Office>> treeMap) {

        List<Office> children = treeMap.get (parent.getId ());
        parent.setChildren (children);
        if (children != null && !children.isEmpty ()) {
            for (Office child : children) {
                formatFillChildren (child, treeMap);
            }
        }
    }


}
